﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace FANUC.BackgroundWorker
{

    public partial class FormMain : Form
    {
        public static bool InProcessing = false;

        public FormMain()
        {
            InitializeComponent();
        }

        private void radioButtonEnable_CheckedChanged(object sender, EventArgs e)
        {
            if (this.radioButtonEnable.Checked == true)
            {
                this.richTextBoxLog.AppendText(System.DateTime.Now + "\tProcess Started\n");
                this.richTextBoxLog.ScrollToCaret();
                //start processing
                this.timerProcesser.Enabled = true;
                //Thread p = new Thread(new ThreadStart(processData));
                //p.Start();
                //started
            }
        }

        private void radioButtonDisable_CheckedChanged(object sender, EventArgs e)
        {
            if (this.radioButtonDisable.Checked == true)
            {
                this.richTextBoxLog.AppendText(System.DateTime.Now + "\tProcess Stopping\n");
                this.richTextBoxLog.ScrollToCaret();
                //stop processing
                this.timerProcesser.Enabled = false;
            }
        }

        public delegate void Process();

        private void timerProcesser_Tick(object sender, EventArgs e)
        {
            if (InProcessing)
            {
                return;
            }
            else
            {
                InProcessing = true;
                Thread p = new Thread(new ThreadStart(processData));
                p.Start();
            }
        }
        private void processData()
        {
            lock (this)
            {
                using (JCIDB db = new JCIDB())
                {
                    try
                    {
                        InProcessing = true;
                        var partUnits = db.Part_Unit.Where(a => a.Quality_Grade == -1 && (db.Pass_Value_History.Where(b => b.Part_Serial == a.Part_Serial).FirstOrDefault() != null)).OrderByDescending(a => a.Start_Time).ToList();
                        foreach (var unit in partUnits)
                        {
                            var passValues = db.Pass_Value_History.Where(a => a.Part_Serial == unit.Part_Serial).ToList();
                            int unitQualityGrade = -1;
                            foreach (var passValue in passValues)
                            {
                                int passQualityGrade = -1;
                                var standardValue = db.Pass_Standard_Value.Where(a => a.Robot_ID == unit.Robot_ID && a.Pass_No == passValue.Pass_No && a.Part_Name == unit.Part_Name).FirstOrDefault();
                                if (standardValue == null)
                                {
                                    unitQualityGrade = -1;
                                    break;
                                }
                                else
                                {
                                    #region Current Assessment
                                    decimal currentLSL = Convert.ToDecimal(standardValue.Current_Standard) - (Convert.ToDecimal(standardValue.Current_Standard) * Convert.ToDecimal(standardValue.Current_Standard_Low_Percent) / 100);
                                    decimal currentUSL = Convert.ToDecimal(standardValue.Current_Standard) + (Convert.ToDecimal(standardValue.Current_Standard) * Convert.ToDecimal(standardValue.Current_Standard_High_Percent) / 100);
                                    decimal qualityCurrentGoodPercentage = Convert.ToDecimal(standardValue.Current_Grade1_Percent) / 100; //Example 10%
                                    decimal qualityCurrentOKPercentage = Convert.ToDecimal(standardValue.Current_Grade2_Percent) / 100; //Example 30%
                                    string[] allCurrentValues = passValue.Data_Current.Split(',');
                                    if (allCurrentValues.Length <= 0)
                                    {
                                        break;
                                    }
                                    allCurrentValues = allCurrentValues.Skip(40).ToArray();
                                    List<decimal> allCurrentValuesDecimal = new List<decimal>();
                                    int exceedCurrentLSLCount = 0;
                                    int exceedCurrentUSLCount = 0;
                                    foreach (string oneCurrentValue in allCurrentValues)
                                    {
                                        decimal convertedOneCurrentValue = Convert.ToDecimal(String.IsNullOrEmpty(oneCurrentValue) == true ? "0" : oneCurrentValue);
                                        if (convertedOneCurrentValue < currentLSL)
                                        {
                                            exceedCurrentLSLCount++;
                                        }
                                        else if (convertedOneCurrentValue > currentUSL)
                                        {
                                            exceedCurrentUSLCount++;
                                        }
                                        allCurrentValuesDecimal.Add(convertedOneCurrentValue);
                                    }
                                    int countOfCurrentValues = allCurrentValuesDecimal.Count;
                                    decimal actualCurrentQualityPercentage = Convert.ToDecimal(exceedCurrentLSLCount + exceedCurrentUSLCount) / countOfCurrentValues;
                                    if (actualCurrentQualityPercentage < qualityCurrentGoodPercentage)
                                    {
                                        //Good
                                        passQualityGrade = 1;
                                    }
                                    else if (actualCurrentQualityPercentage > qualityCurrentOKPercentage)
                                    {
                                        //NG
                                        passQualityGrade = 3;

                                    }
                                    else
                                    {
                                        //OK
                                        passQualityGrade = 2;
                                    }
                                    #endregion

                                    #region Voltage Assessment
                                    decimal voltageLSL = Convert.ToDecimal(standardValue.Voltage_Standard) - (Convert.ToDecimal(standardValue.Voltage_Standard) * Convert.ToDecimal(standardValue.Voltage_Standard_Low_Percent) / 100);
                                    decimal voltageUSL = Convert.ToDecimal(standardValue.Voltage_Standard) + (Convert.ToDecimal(standardValue.Voltage_Standard) * Convert.ToDecimal(standardValue.Voltage_Standard_High_Percent) / 100);
                                    decimal qualityVoltageGoodPercentage = Convert.ToDecimal(standardValue.Voltage_Grade1_Percent) / 100; //Example 10%
                                    decimal qualityVoltageOKPercentage = Convert.ToDecimal(standardValue.Voltage_Grade2_Percent) / 100; //Example 30%
                                    string[] allVoltageValues = passValue.Data_Voltage.Split(',');
                                    if (allVoltageValues.Length <= 0)
                                    {
                                        break;
                                    }
                                    allVoltageValues = allVoltageValues.Skip(40).ToArray();
                                    List<decimal> allVoltageValuesDecimal = new List<decimal>();
                                    int exceedVoltageLSLCount = 0;
                                    int exceedVoltageUSLCount = 0;
                                    foreach (string oneVoltageValue in allVoltageValues)
                                    {
                                        decimal convertedOneVoltageValue = Convert.ToDecimal(String.IsNullOrEmpty(oneVoltageValue) == true ? "0" : oneVoltageValue);
                                        if (convertedOneVoltageValue < voltageLSL)
                                        {
                                            exceedVoltageLSLCount++;
                                        }
                                        else if (convertedOneVoltageValue > voltageUSL)
                                        {
                                            exceedVoltageUSLCount++;
                                        }
                                        allVoltageValuesDecimal.Add(convertedOneVoltageValue);
                                    }
                                    int countOfVoltageValues = allVoltageValuesDecimal.Count;
                                    decimal actualVoltageQualityPercentage = Convert.ToDecimal(exceedVoltageLSLCount + exceedVoltageUSLCount) / countOfVoltageValues;
                                    if (actualVoltageQualityPercentage < qualityVoltageGoodPercentage)
                                    {
                                        //Good
                                        if (1 > passQualityGrade)
                                        { passQualityGrade = 1; }
                                    }
                                    else if (actualVoltageQualityPercentage > qualityVoltageOKPercentage)
                                    {
                                        //NG
                                        passQualityGrade = 3;

                                    }
                                    else
                                    {
                                        //OK
                                        if (2 > passQualityGrade)
                                        { passQualityGrade = 2; }
                                    }
                                    #endregion

                                    if (passQualityGrade != -1)
                                    {
                                        passValue.Quality_Grade = passQualityGrade;
                                        passValue.Current_Real_Over_Percent = actualCurrentQualityPercentage;
                                        passValue.Voltage_Real_Over_Percent = actualVoltageQualityPercentage;
                                        if (passQualityGrade > unitQualityGrade)
                                        {
                                            unitQualityGrade = passQualityGrade;
                                        }
                                        db.Entry(passValue).State = System.Data.Entity.EntityState.Modified;
                                    }
                                }
                            }
                            if (unitQualityGrade == -1)
                            {
                                continue;
                            }
                            else
                            {
                                unit.Quality_Grade = unitQualityGrade;
                                db.Entry(unit).State = System.Data.Entity.EntityState.Modified;
                            }

                            db.SaveChanges();
                        }
                    }
                    catch (Exception ex)
                    {
                        this.richTextBoxLog.AppendText(System.DateTime.Now + "\n" + ex.ToString() + "\n");
                        this.richTextBoxLog.ScrollToCaret();
                    }
                    InProcessing = false;
                }
            }
        }

        private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(-1);
        }
    }
}
